package com.solo.system.mapper;

import com.mybatisflex.core.query.QueryChain;
import com.solo.common.core.utils.ServletUtils;
import com.solo.satoken.utils.LoginHelper;
import com.solo.system.api.consts.global.GlobalStatus;
import com.solo.system.api.entity.SysMenu;
import com.solo.common.core.base.mapper.BasicMapper;
import com.solo.system.model.menu.resp.MenuRoutersResp;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

import static com.mybatisflex.core.query.QueryMethods.distinct;
import static com.solo.system.api.entity.table.SysI18nDataTableDef.SysI18nDataTable;
import static com.solo.system.api.entity.table.SysI18nTypeDataTableDef.SysI18nTypeDataTable;
import static com.solo.system.api.entity.table.SysI18nTypeTableDef.SysI18nTypeTable;
import static com.solo.system.api.entity.table.SysMenuTableDef.SysMenuTable;
import static com.solo.system.api.entity.table.SysRoleMenuTableDef.SysRoleMenuTable;
import static com.solo.system.api.entity.table.SysRoleTableDef.SysRoleTable;
import static com.solo.system.api.entity.table.SysUserRoleTableDef.SysUserRoleTable;
import static com.solo.system.api.entity.table.SysUserTableDef.SysUserTable;

/**
 * 菜单 Mapper
 * @author 十一
 * @since 2023-11-14 14:13
 * 人生若只如初见，何事秋风悲画扇
 **/
@Mapper
public interface SysMenuMapper extends BasicMapper<SysMenu> {

    default List<MenuRoutersResp> routers() {
        return QueryChain.of(this)
                .select(distinct(SysMenuTable.AllColumns, SysI18nTypeDataTable.Translate))
                .from(SysI18nTypeDataTable)
                .innerJoin(SysI18nTypeTable).on(
                        SysI18nTypeDataTable.TypeId.eq(SysI18nTypeTable.TypeId)
                                .and(SysI18nTypeTable.Name.eq(ServletUtils.getAcceptLanguage()))
                                .and(SysI18nTypeTable.Status.eq(true))
                )
                .leftJoin(SysI18nDataTable).on(SysI18nTypeDataTable.DataId.eq(SysI18nDataTable.DataId))
                .rightJoin(SysMenuTable).on(SysMenuTable.Name.eq(SysI18nDataTable.Key))
                .leftJoin(SysRoleMenuTable).on(SysMenuTable.MenuId.eq(SysRoleMenuTable.MenuId))
                .leftJoin(SysUserRoleTable).on(SysRoleMenuTable.RoleId.eq(SysUserRoleTable.RoleId))
                .leftJoin(SysRoleTable).on(SysUserRoleTable.RoleId.eq(SysRoleTable.RoleId))
                .leftJoin(SysUserTable).on(SysUserRoleTable.UserId.eq(SysUserTable.UserId))
                .where(SysUserTable.UserId.eq(LoginHelper.getUserId()))
                // TODO 类型改成枚举
                .and(SysMenuTable.Type.in("D", "M"))
                .and(SysRoleTable.Status.eq(GlobalStatus.NORMAL))
                .orderBy(SysMenuTable.ParentId.desc(), SysMenuTable.Sort.desc())
                .listAs(MenuRoutersResp.class);
    }

}
